package com.tianyuan.lims.dms.controller.exam;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.tianyuan.lims.common.render.InputStreamRender;
import com.tianyuan.lims.dms.controller.exam.service.QuestionImportService;
import com.tianyuan.lims.dms.entity.LimsCategory;
import com.tianyuan.lims.dms.entity.LimsExamQuestion;
import io.github.yedaxia.apidocs.ApiDoc;
import com.tianyuan.lims.utils.R;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class LimsCategoryController extends Controller {
    @ApiDoc(url = "/LimsCategory/save", method = "post")
    public void save() {
        LimsCategory model = getModel(LimsCategory.class);
        if (model.save()) {
            renderJson(R.ok("保存成功"));
        } else {
            renderJson(R.ok("保存失败"));
        }
    }
    @ApiDoc(url = "/LimsCategory/get", method = "post")
    public void get() {
        int id = getParaToInt();
        LimsCategory model = LimsCategory.dao.findById(id);
        if (model != null) {
            renderJson(R.ok().put("data", model));
        } else {
            renderJson(R.ok("未找到记录"));
        }
    }
    @ApiDoc(url = "/LimsCategory/update", method = "post")
    public void update() {
        LimsCategory model = getModel(LimsCategory.class);
        if (model.update()) {
            renderJson(R.ok("更新成功"));
        } else {
            renderJson(R.ok("更新失败"));
        }
    }
    @ApiDoc(url = "/LimsCategory/delete", method = "post")
    public void delete() {
        int id = getParaToInt();
        if (LimsCategory.dao.deleteById(id)) {
            renderJson(R.ok("删除成功"));
        } else {
            renderJson(R.ok("删除失败"));
        }
    }


    /**
     * 获取知识点分类树形结构（供前端级联选择器使用）
     * 层级最多8级，返回格式：[{value: id, label: name, children: [...]}, ...]
     */
    @ApiDoc(url = "/LimsCategory/getTree", method = "get")
    public void getTree() {
        try {
            // 1. 用Record查询分类（Record本质是Map，无序列化权限问题）
            List<Record> allCategories = Db.find(
                    "select id, name, parentId, level from lims_Category where status=1 and isAudited=1 order by parentId, sort"
            );

            // 2. 构建树形结构（基于Record）
            List<Record> treeData = buildTree(allCategories, 0);

            renderJson(R.ok().put("data", treeData));
        } catch (Exception e) {
            renderJson(R.error(e.getMessage()));
        }
    }

    // 递归构建树形（Record版）
    private List<Record> buildTree(List<Record> all, Integer parentId) {
        List<Record> children = new ArrayList<>();
        for (Record r : all) {
            if (r.getInt("parentId").equals(parentId)) {
                // 复制当前节点的必要字段
                Record node = new Record();
//                node.set("id", r.getInt("id"));
                node.set("value", r.getInt("id"));
                node.set("text", r.getStr("name"));

                // 处理子节点
                if (r.getInt("level") < 8) {
                    node.set("children", buildTree(all, r.getInt("id")));
                } else {
                    node.set("children", new ArrayList<>());
                }
                children.add(node);
            }
        }
        return children;
    }


    // 递归构建树形（Record版）
    private List<Record> buildTreeExpanded(List<Record> all, Integer parentId) {
        List<Record> children = new ArrayList<>();
        for (Record r : all) {
            if (r.getInt("parentId").equals(parentId)) {
                // 复制当前节点的必要字段
                Record node = new Record();
                node.set("expanded", true);
                node.set("weight", 0);
                node.set("id", r.getInt("id") + "");
                node.set("name", r.getStr("name"));
                if (r.getInt("level") < 8) {
                    node.set("children", buildTreeExpanded(all, r.getInt("id")));
                } else {
                    node.set("children", new ArrayList<>());
                }
                children.add(node);
            }
        }
        return children;
    }

    private final QuestionImportService importService = new QuestionImportService();

    /**
     * 批量导入题目
     */
    @ApiDoc(url = "/limsCategory/batchImport", method = "post")
    public void batchImport() {
        try {
            // 获取上传文件
            UploadFile uploadFile = getFile("file");
            if (uploadFile == null) {
                renderJson(R.error("请选择文件"));
                return;
            }

            // 验证文件大小
            long fileSize = uploadFile.getFile().length();
            if (fileSize > 50 * 1024 * 1024) { // 50MB
                uploadFile.getFile().delete(); // 删除临时文件
                renderJson(R.error("单文件最大50MB，单次最多导入1000道题，支持.xlsx/.xls/UTF-8编码CSV格式"));
                return;
            }

            // 获取分类ID
            Integer categoryId = getParaToInt("categoryId");
            if (categoryId == null) {
                renderJson(R.error("请选择知识点分类"));
                return;
            }

            // 解析文件并导入
            String fileName = uploadFile.getFileName();
            String taskId = importService.importQuestions(uploadFile.getFile(), fileName, categoryId);

            renderJson(R.ok().put("data", taskId));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(R.error("导入失败：" + e.getMessage()));
        }
    }

    /**
     * 获取导入预览数据
     * @param taskId 导入任务ID
     */
    @ApiDoc(url = "/question/importPreview", method = "get")
    public void importPreview() {
        String taskId = getPara("taskId");
        List<LimsExamQuestion> previewList = importService.getImportPreview(taskId, 10); // 最多10条
        int totalCount = importService.getTotalCount(taskId);
        int errorCount = importService.getErrorCount(taskId);
        renderJson(R.ok()
                .put("list", previewList)
                .put("totalCount", totalCount)
                .put("errorCount", errorCount)
        );
    }

    /**
     * 确认导入
     * @param taskId 导入任务ID
     */
    @ApiDoc(url = "/question/confirmImport", method = "post")
    public void confirmImport() {
        String taskId = getPara("taskId");
        boolean success = importService.confirmImport(taskId);
        if (success) {
            renderJson(R.ok("导入成功"));
        } else {
            renderJson(R.error("导入失败"));
        }
    }

    /**
     * 下载错误列表
     * @param taskId 导入任务ID
     */
    @ApiDoc(url = "/question/downloadErrorList", method = "get")
    public void downloadErrorList() {
        String taskId = getPara("taskId");
        importService.downloadErrorList(taskId, getResponse());
    }

    /**
     * 下载导入模版
     */
    public void downloadTemplate() {
        // 模板文件名（根据实际文件名修改）
        String fileName = "question_import_template.xlsx";
        // 模板文件在 resources 中的路径（编译后会在 classes 目录下）
        String templatePath = "template/lims/" + fileName;

        try {
            // 通过类加载器获取文件输入流（兼容打包后的 JAR/WAR）
            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(templatePath);
            if (inputStream == null) {
                // 文件不存在时的处理
                renderText("模板文件不存在");
                return;
            }

            // 设置响应头，指定文件名（解决中文乱码问题）
            String encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            getResponse().setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
            getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // xlsx 类型

            // 输出文件流
            //renderFile(templatePath, fileName);// inputStream
            render(new InputStreamRender(inputStream, fileName, getResponse()));

        } catch (Exception e) {
            e.printStackTrace();
            renderText("下载失败：" + e.getMessage());
        }
    }


    /**
     * 获取知识点分类树形结构（供前端级联选择器使用）
     * 层级最多8级，返回格式：[{value: id, label: name, children: [...]}, ...]
     */
    @ApiDoc(url = "/LimsCategory/getTreeExpanded", method = "get")
    public void getTreeExpanded() {
        try {
            // 1. 用Record查询分类（Record本质是Map，无序列化权限问题）
            List<Record> allCategories = Db.find(
                    "select id, name, parentId, level from lims_Category where status=1 and isAudited=1 order by parentId, sort"
            );

            // 2. 构建树形结构（基于Record）
            List<Record> treeData = buildTreeExpanded(allCategories, 0);

            renderJson(R.ok().put("data", treeData));
        } catch (Exception e) {
            renderJson(R.error(e.getMessage()));
        }
    }

}
